﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.IO;
using Microsoft.WindowsAzure.Storage.Table;
using System.Threading;

namespace Blob_Watcher
{
    class Program
    {        
        static void Main(string[] args)
        {
            // set up our private variables.
            string storageAccountString = Properties.Settings.Default.AzureStorageConnection;

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccountString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // make sure we have a gatekeerp in place
            CloudBlobContainer gatekeeperContainer = blobClient.GetContainerReference("gatekeeper");
            gatekeeperContainer.CreateIfNotExists(); // want to make sure the container is there... 
            CloudBlockBlob gatekeeperBlob = gatekeeperContainer.GetBlockBlobReference("gatekeeper");
            Gatekeeper mygatekeeper = new Gatekeeper(gatekeeperBlob, "blob/");

            // initialize the log scanner
            LogScanner myScanner = new LogScanner(blobClient, mygatekeeper);
            myScanner.ScanInterval = new TimeSpan(0, 5, 0);
            myScanner.Start(LogFound);

            // run for 1 hr
            for (int i=0; i<=60; i++)
            {
                // sleep for 1 minute
                Thread.Sleep(60000);
            }

            myScanner.Stop();
        }

        /// <summary>
        /// Found a log file, lets act on it. 
        /// </summary>
        /// <param name="LogBlob"></param>
        public static void LogFound(CloudBlockBlob LogBlob)
        {
            Console.WriteLine(string.Format("Parsing Log File: {0}", LogBlob.Uri));

            // Parse the Log
            LogParser myParser = new LogParser(LogBlob);
            //HINT: we could drop the log file into a queue and process asyncronously
            myParser.ParseFile(FoundBlob);

            //Option: delete the log once its processed
        }

        /// <summary>
        /// Found a blob, will filter found files here.. 
        /// </summary>
        /// <param name="newBlobUri"></param>
        public static void FoundBlob(string newBlobUri)
        {
            // filter however you like, by container, file name, etc... 
            if (!newBlobUri.Contains("gatekeeper")) // ignore gatekeeper updates
                Console.WriteLine(string.Format("Found new blob: {0}", newBlobUri));
        }
    }
}

